package com.lilicould.controller;

import com.google.gson.Gson;
import com.lilicould.entity.TeacherDetails;
import com.lilicould.service.TeacherService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

import static jakarta.servlet.http.HttpServletResponse.*;

@WebServlet("/teacher/*")
public class TeacherController extends BaseServlet{
    public void listAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        String result = new TeacherService().getAllTeachers();
        out.write(result);
    }

    public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        Gson gson = new Gson();
        PrintWriter out = resp.getWriter();

        // 获取请求中的json数据
        String json = req.getReader().readLine();
        TeacherDetails teacherDetails = gson.fromJson(json, TeacherDetails.class);

        // 调用服务层添加教师信息
        String result = new TeacherService().addTeacher(teacherDetails);
        if (result != null) {
            resp.setStatus(SC_BAD_REQUEST);
            out.write(gson.toJson(result));
        } else {
            resp.setStatus(SC_OK);
        }

    }

    public void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        String result = new TeacherService().deleteTeacher(req.getParameter("userNo"));
        if (result != null) {
            resp.setStatus(SC_BAD_REQUEST);
            out.write(new Gson().toJson(result));
        } else {
            resp.setStatus(SC_OK);
        }
    }

    // 获取教师信息
    public void get(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        // 获取参数
        String userNo = req.getParameter("userNo");

        // 调用服务层获取教师信息
        String result = new TeacherService().getTeacher(userNo);
        if (result != null) {
            // 成功获取到教师信息
            resp.setStatus(SC_OK);
            resp.getWriter().write(result);
        } else {
            // 未获取到教师信息
            resp.setStatus(SC_NOT_FOUND);
        }
    }
}
